package com.wzy.netty.core.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * 描述
 * 创建人    Wzy
 * 创建时间: 2020-05-23  1:06
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //使用客户端发送信息
        for (int i = 0; i < 5; i++) {
            String msg = "今天天气冷,去吃火锅";
            byte[] content = msg.getBytes(Charset.forName("utf-8"));
            int length = msg.getBytes(Charset.forName("utf-8")).length;

            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(length);
            messageProtocol.setContent(content);
            ctx.writeAndFlush(messageProtocol);

        }
    }
//
//    @Override
//    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
//        byte[] buffer = new byte[msg.readableBytes()];
//        msg.readBytes(buffer);
//        String message = new String(buffer, CharsetUtil.UTF_8);
//        System.out.println("客户端接收到消息:" + message);
//        System.out.println("客户端接搜消息数量=" + (++this.count));
//    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端接收消息如下:长度=" + len);
        System.out.println("内容" + new String(content, CharsetUtil.UTF_8));
        System.out.println("客户端接收到消息包数量:" + (++this.count));

    }
}
